package com.pilipili.serverapi.config;

import com.pilipili.common.Exception.BusinessRuntimeException;
import com.pilipili.serverapi.ErrorCode;
import com.pilipili.serverapi.manageUser.entity.ManageUser;
import com.pilipili.serverapi.manageUser.entity.Permission;
import com.pilipili.serverapi.manageUser.entity.Role;
import com.pilipili.serverapi.manageUser.service.ManageUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;

@Slf4j
public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    private ManageUserService manageUserService;
    @Autowired
    private static final Logger LOG = LoggerFactory.getLogger(ShiroRealm.class);
    /**
     * 认证信息.(身份验证) : Authentication 是用来验证用户身份
     *
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        log.info("---------------- 执行 Shiro 凭证认证 ----------------------");
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String name = token.getUsername();
        // 从数据库获取对应用户名密码的用户
        ManageUser manageUser = manageUserService.findUserByUserName(name);
        if (manageUser != null) {
            log.info("---------------- Shiro 凭证认证成功 ----------------------");
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                    manageUser, //用户
                    manageUser.getPassword(), //密码
                    getName()  //realm name
            );
            LOG.info("testtestetsettest");
            return authenticationInfo;
        }
        throw new UnknownAccountException();
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.info("---------------- 执行 Shiro 权限获取 ---------------------");
        Object principal = principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if (principal instanceof ManageUser) {
            ManageUser userLogin = (ManageUser) principal;
            if(userLogin != null){
                Set<Role> roles = manageUserService.findRolesByUserId(userLogin.getId());
                if(!roles.isEmpty()){
                    for(Role role : roles){
                        LOG.info(role.getRoleName());
                        info.addRole(role.getRoleName());
                        Set<Permission> permissions = manageUserService.findPermissionsByUserId(userLogin.getId());
                        if(!permissions.isEmpty()){
                            for (Permission permission : permissions){
                                if(StringUtils.isNoneBlank(permission.getPermissionName())){
                                    LOG.info(permission.getPermissionName());
                                    info.addStringPermission(permission.getPermissionName());
                                }
                            }
                        }
                    }
                }
            }
        }
        log.info("---------------- 获取到以下权限 ----------------");
        if(info !=  null && info.getStringPermissions() != null)
        log.info(info.getStringPermissions().toString());
        log.info("---------------- Shiro 权限获取成功 ----------------------");
        return info;
    }
}